import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';

/// 树组件尺寸
enum ETreeSize {
  /// 小型
  small,
  
  /// 中型
  medium,
  
  /// 大型
  large,
}

/// 树节点数据结构
class ETreeNode<T> {
  /// 节点图标
  final IconData? icon;
  
  /// 节点自定义操作图标（鼠标悬停时显示）
  final List<Widget>? actionIcons;
  /// 创建ETreeNode
  ETreeNode({
    required this.id,
    this.label,
    this.data,
    this.icon,
    this.actionIcons,
    this.children = const [],
    this.expanded = false,
    this.checked = false,
    this.disabled = false,
    this.isLeaf = false,
  });

  /// 节点ID
  final String id;
  
  /// 节点标签（显示文本）
  final String? label;
  
  /// 节点关联数据
  final T? data;
  
  /// 子节点列表
  final List<ETreeNode<T>> children;
  
  /// 是否展开
  bool expanded;
  
  /// 是否选中
  bool checked;
  
  /// 是否禁用
  final bool disabled;
  
  /// 是否为叶子节点
  final bool isLeaf;
  
  /// 是否有子节点
  bool get hasChildren => children.isNotEmpty && !isLeaf;
}

/// 树组件选择类型
enum ETreeSelectType {
  /// 单选
  single,
  
  /// 多选
  multiple,
  
  /// 禁止选择
  none,
}

/// 树组件
class ETree<T> extends StatefulWidget {
  /// 创建ETree组件
  const ETree({
    super.key,
    required this.data,
    this.height,
    this.emptyText = '暂无数据',
    this.selectable = true,
    this.selectType = ETreeSelectType.single,
    this.checkStrictly = false,
    this.expandOnClickNode = false,
    this.checkOnClickNode = false,
    this.defaultExpandedKeys = const [],
    this.defaultCheckedKeys = const [],
    this.onNodeClick,
    this.onCheckChange,
    this.onExpandChange,
    this.renderContent,
    this.size = ETreeSize.medium,
  });

  /// 树组件尺寸
  final ETreeSize size;

  /// 树数据
  final List<ETreeNode<T>> data;
  
  /// 树组件高度
  final double? height;
  
  /// 空数据提示文本
  final String emptyText;
  
  /// 是否可选择
  final bool selectable;
  
  /// 选择类型
  final ETreeSelectType selectType;
  
  /// 是否严格遵循父子不互相关联
  final bool checkStrictly;
  
  /// 点击节点时是否展开或折叠节点
  final bool expandOnClickNode;
  
  /// 点击节点文本时是否切换勾选状态
  final bool checkOnClickNode;
  
  /// 默认展开的节点ID列表
  final List<String> defaultExpandedKeys;
  
  /// 默认选中的节点ID列表
  final List<String> defaultCheckedKeys;
  
  /// 节点点击回调
  final Function(ETreeNode<T>, int)? onNodeClick;
  
  /// 节点勾选状态变更回调
  final Function(List<String>)? onCheckChange;
  
  /// 节点展开/折叠状态变更回调
  final Function(String, bool)? onExpandChange;
  
  /// 自定义节点内容渲染
  final Widget Function(BuildContext, ETreeNode<T>, int)? renderContent;
  
  @override
  ETreeState<T> createState() => ETreeState<T>();
}

class ETreeState<T> extends State<ETree<T>> {
  /// 当前选中的节点ID
  String? _selectedNodeId;
  
  /// 当前悬停的节点ID
  String? _hoveredNodeId;
  
  /// 根据尺寸获取垂直内边距
  double get _verticalPadding {
    switch (widget.size) {
      case ETreeSize.small:
        return 4.0;
      case ETreeSize.large:
        return 8.0;
      default:
        return 6.0;
    }
  }
  
  /// 根据尺寸获取字体大小
  double get _fontSize {
    switch (widget.size) {
      case ETreeSize.small:
        return 12.0;
      case ETreeSize.large:
        return 16.0;
      default:
        return 14.0;
    }
  }
  
  /// 根据尺寸获取图标大小
  double get _iconSize {
    switch (widget.size) {
      case ETreeSize.small:
        return 14.0;
      case ETreeSize.large:
        return 18.0;
      default:
        return 16.0;
    }
  }
  
  /// 初始化树数据
  @override
  void initState() {
    super.initState();
    
    // 设置默认展开的节点
    for (final key in widget.defaultExpandedKeys) {
      _setNodeExpanded(widget.data, key, true);
    }
    
    // 设置默认选中的节点
    if (widget.selectType == ETreeSelectType.single && widget.defaultCheckedKeys.isNotEmpty) {
      _selectedNodeId = widget.defaultCheckedKeys.first;
      _setNodeChecked(widget.data, _selectedNodeId!, true);
    } else if (widget.selectType == ETreeSelectType.multiple) {
      for (final key in widget.defaultCheckedKeys) {
        _setNodeChecked(widget.data, key, true);
      }
    }
  }
  
  /// 递归设置节点展开状态
  bool _setNodeExpanded(List<ETreeNode<T>> nodes, String nodeId, bool expanded) {
    for (final node in nodes) {
      if (node.id == nodeId) {
        node.expanded = expanded;
        if (widget.onExpandChange != null) {
          widget.onExpandChange!(nodeId, expanded);
        }
        return true;
      }
      
      if (node.children.isNotEmpty) {
        if (_setNodeExpanded(node.children, nodeId, expanded)) {
          return true;
        }
      }
    }
    return false;
  }
  
  /// 递归设置节点选中状态
  bool _setNodeChecked(List<ETreeNode<T>> nodes, String nodeId, bool checked) {
    for (final node in nodes) {
      if (node.id == nodeId) {
        if (!node.disabled) {
          node.checked = checked;
          
          // 处理父子节点联动
          if (!widget.checkStrictly) {
            // 更新所有子节点
            _updateAllChildren(node.children, checked);
            
            // 更新父节点
            _updateParentCheckedState(widget.data, nodeId);
          }
        }
        return true;
      }
      
      if (node.children.isNotEmpty) {
        if (_setNodeChecked(node.children, nodeId, checked)) {
          return true;
        }
      }
    }
    return false;
  }
  
  /// 更新所有子节点的选中状态
  void _updateAllChildren(List<ETreeNode<T>> children, bool checked) {
    for (final child in children) {
      if (!child.disabled) {
        child.checked = checked;
      }
      if (child.children.isNotEmpty) {
        _updateAllChildren(child.children, checked);
      }
    }
  }
  
  /// 更新父节点的选中状态
  void _updateParentCheckedState(List<ETreeNode<T>> nodes, String childId) {
    for (final node in nodes) {
      for (final child in node.children) {
        if (child.id == childId) {
          // 计算当前节点的选中状态
          final allChecked = child.children.isNotEmpty 
            ? child.children.every((c) => c.checked)
            : child.checked;
          
          if (!node.disabled) {
            node.checked = allChecked;
          }
          
          // 递归更新父节点
          _updateParentCheckedState(widget.data, node.id);
          return;
        }
        
        if (child.children.isNotEmpty) {
          _updateParentCheckedState(child.children, childId);
        }
      }
    }
  }
  
  /// 处理节点点击
  void _handleNodeClick(ETreeNode<T> node, int level) {
    // 触发点击回调
    if (widget.onNodeClick != null) {
      widget.onNodeClick!(node, level);
    }
    
    // 处理单选逻辑
    if (widget.selectable && widget.selectType == ETreeSelectType.single && !node.disabled) {
      setState(() {
        if (_selectedNodeId != null) {
          _setNodeChecked(widget.data, _selectedNodeId!, false);
        }
        _selectedNodeId = node.id;
        _setNodeChecked(widget.data, node.id, true);
        
        // 触发选中回调
        if (widget.onCheckChange != null) {
          widget.onCheckChange!([node.id]);
        }
      });
    }
    
    // 点击节点时展开/折叠
    if (widget.expandOnClickNode && node.hasChildren && !node.disabled) {
      setState(() {
        _setNodeExpanded(widget.data, node.id, !node.expanded);
      });
    }
  }
  
  /// 处理节点勾选
  void _handleCheckChange(ETreeNode<T> node, bool checked) {
    if (node.disabled) {
      return;
    }
    
    setState(() {
      _setNodeChecked(widget.data, node.id, checked);
      
      // 触发选中回调
      if (widget.onCheckChange != null) {
        final checkedKeys = _getCheckedKeys(widget.data);
        widget.onCheckChange!(checkedKeys);
      }
    });
  }
  
  /// 处理展开/折叠按钮点击
  void _handleExpandClick(ETreeNode<T> node) {
    if (!node.disabled) {
      setState(() {
        _setNodeExpanded(widget.data, node.id, !node.expanded);
      });
    }
  }
  
  /// 获取所有选中的节点ID
  List<String> _getCheckedKeys(List<ETreeNode<T>> nodes) {
    final List<String> keys = [];
    
    for (final node in nodes) {
      if (node.checked) {
        keys.add(node.id);
      }
      
      if (node.children.isNotEmpty) {
        keys.addAll(_getCheckedKeys(node.children));
      }
    }
    
    return keys;
  }
  
  /// 构建树结构
  Widget _buildTree() {
    if (widget.data.isEmpty) {
      return _buildEmptyState();
    }
    
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: widget.data.map((node) {
          return _buildTreeNode(node, 0);
        }).toList(),
      ),
    );
  }
  
  /// 处理鼠标进入节点
  void _handleMouseEnter(String nodeId) {
    setState(() {
      _hoveredNodeId = nodeId;
    });
  }
  
  /// 处理鼠标离开节点
  void _handleMouseLeave() {
    setState(() {
      _hoveredNodeId = null;
    });
  }
  
  /// 递归构建树节点
  Widget _buildTreeNode(ETreeNode<T> node, int level) {
    final theme = EleganceTheme.of(context);
    final indent = level * 20.0;
    final isHovered = _hoveredNodeId == node.id;
    
    // 节点内容
    Widget content;
    if (widget.renderContent != null) {
      content = widget.renderContent!(context, node, level);
    } else {
      // 基础内容（图标+文本）
      final List<Widget> contentItems = [];
      
      // 添加节点图标（如果有）
      if (node.icon != null) {
        contentItems.add(
          Padding(
            padding: const EdgeInsets.only(right: 8.0),
            child: Icon(
              node.icon,
              size: _iconSize,
              color: node.disabled 
                ? theme.textPlaceholderColor 
                : theme.textRegularColor,
            ),
          ),
        );
      }
      
      // 添加文本
      contentItems.add(
        Text(
          node.label ?? node.id,
          style: TextStyle(
            color: node.disabled 
              ? theme.textPlaceholderColor 
              : theme.textRegularColor,
            fontSize: _fontSize,
          ),
        ),
      );
      
      content = Row(children: contentItems);
    }
    
    // 节点行
    final nodeRow = MouseRegion(
      onEnter: (_) => _handleMouseEnter(node.id),
      onExit: (_) => _handleMouseLeave(),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: _verticalPadding),
        color: _selectedNodeId == node.id && !node.disabled 
            ? theme.primaryLight 
            : (isHovered && !node.disabled ? theme.surfaceColor : null),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 展开/折叠按钮
            if (node.hasChildren) ...[
              GestureDetector(
                onTap: () => _handleExpandClick(node),
                child: Container(
                  width: 20.0,
                  height: 20.0,
                  alignment: Alignment.center,
                  child: Icon(
                    node.expanded 
                      ? Icons.arrow_drop_down 
                      : Icons.arrow_right,
                    size: _iconSize,
                    color: theme.textRegularColor,
                  ),
                ),
              ),
            ] else ...[
              // 空白占位
              const SizedBox(width: 20.0),
            ],
            
            // 复选框
            if (widget.selectable && widget.selectType == ETreeSelectType.multiple) ...[
              Checkbox(
                value: node.checked,
                onChanged: node.disabled 
                  ? null 
                  : (checked) => _handleCheckChange(node, checked ?? false),
                activeColor: theme.primaryColor,
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
            ],
            
            // 内容区域
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: indent),
                child: GestureDetector(
                  onTap: () => _handleNodeClick(node, level),
                  child: content,
                ),
              ),
            ),
            
            // 添加操作图标（如果有且鼠标悬停）
            if (isHovered && node.actionIcons != null && node.actionIcons!.isNotEmpty && !node.disabled) ...[
              const SizedBox(width: 8.0),
              Row(
                children: node.actionIcons!,
              ),
            ],
          ],
        ),
      ),
    );
    
    // 子节点
    final List<Widget> childrenWidgets = [];
    
    if (node.expanded && node.children.isNotEmpty) {
      for (final childNode in node.children) {
        childrenWidgets.add(_buildTreeNode(childNode, level + 1));
      }
    }
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        nodeRow,
        ...childrenWidgets,
      ],
    );
  }
  
  /// 构建空数据状态
  Widget _buildEmptyState() {
    final theme = EleganceTheme.of(context);
    
    return Container(
      height: widget.height ?? 300.0,
      alignment: Alignment.center,
      child: Text(
        widget.emptyText,
        style: TextStyle(
          color: theme.textPlaceholderColor,
          fontSize: 16.0,
        ),
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
      height: widget.height,
      decoration: BoxDecoration(
        border: Border.all(color: EleganceTheme.of(context).borderColor),
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: _buildTree(),
    );
  }
}